package com.tunan.utils;

import java.io.IOException;
import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.exception.NotFoundUserInfoException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tunan.persistence.model.TSysUser;
import com.tunan.persistence.model.TSysUserLoginTn;
import com.tunan.system.service.SysUserLoginService;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 
 * @ClassName: UserInfoUtils
 * @Description: 用户资料获取工具。可以从REDIS或数据库中获取用。如果redis服务器存在就从REDIS中获取，否则从用户表中获取。
 * @author: kinda
 * @date: 2016年4月12日 上午11:05:17
 */
@Component
public class UserInfoUtils {
	@Resource
	private RedisUtils redisUtils;

	@Autowired
	private SysUserLoginService sysUserLoginService;

	private static UserInfoUtils userInfoUtils;

	@PostConstruct
	public void init() {
		userInfoUtils = this;
	}

	public static TSysUser getTSysUser(String accessToken) {
		Optional<String> token = Optional.ofNullable(accessToken);
		if (token.isPresent()) {
			Optional<String> userInfo = Optional.empty();
			if (userInfoUtils.redisUtils.isRedisLived()) {
				Jedis jedis = null;
				try {
					JedisPool jedisPool = userInfoUtils.redisUtils.getJedisPool();
					jedis = jedisPool.getResource();
					userInfo = Optional.ofNullable(jedis.get(token.get()));
				} catch (Exception e) {
					new NotFoundUserInfoException("用户没有发现");
				} finally {
					if (jedis != null) {
						userInfoUtils.redisUtils.jedisClose(jedis);
					}
				}
			} else {
				Optional<TSysUserLoginTn> userLoginTn = userInfoUtils.sysUserLoginService.selectByToken(token.get());
				userInfo = Optional.ofNullable(userLoginTn.get().getContent());
			}
			ObjectMapper objectMapper = new ObjectMapper();
			if (userInfo.isPresent()) {
				try {
					TSysUser user = objectMapper.readValue(userInfo.get(), TSysUser.class);
					return user;
				} catch (IOException e) {
					throw new NotFoundUserInfoException("用户数据不正常");
				}
			}
		}
		return null;
	}
}
